package com.alkalinesolutions.json.compat;

import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

/** Helper class, as JSONObject does not have an entry iterator
 * 
 * @author David Waite &lt;<a href='mailto:david@alkaline-solutions.com'>david@alkaline-solutions.com</a>&gt;
 *
 */
public class JSONObjectIterator implements Iterator<Map.Entry<String, Object>> {

	JSONObject object;
	private Iterator<String> keyIterator;
	
	class Entry implements Map.Entry<String, Object> {
		private String key;
		private Object value;
		public Entry (String key, Object value) {
			this.key = key;
			this.value = value;
		}
		public String getKey() {
			return key;
		}
		public Object getValue() {
			return value;
		}
		public Object setValue(Object newValue) {
			try {
				JSONObjectIterator.this.object.put(key, newValue);
			} catch (JSONException e) {
				throw new RuntimeException(e);
			}
			Object oldValue = this.value;
			this.value = newValue;
			return oldValue;
		}
	}
	public JSONObjectIterator(JSONObject object) {
		if (object == null)
			throw new IllegalArgumentException("object"); //$NON-NLS-1$
		this.object = object;
		@SuppressWarnings("unchecked")
		Iterator<String> keys = this.object.keys();
		this.keyIterator = keys;
	}
	public boolean hasNext() {
		return keyIterator.hasNext();
	}

	public Entry next() {
		String key = keyIterator.next();
		Object value;
		try {
			value = object.get(key);
		} catch (JSONException e) {
			throw new ConcurrentModificationException(key);
		}
		return new Entry(key, value);
	}

	public void remove() {
		keyIterator.remove();
	}

}
